<template>
    <div class="testcase-container">
      <div class="header">
        <h1>测试用例生成</h1>
        <el-button @click="$router.push('/')" type="text">返回聊天</el-button>
      </div>
      
      <div class="content">
        <div class="left-panel">
          <div class="screenshot-area">
            <div v-if="currentScreenshot" class="screenshot">
              <img :src="imageUrl" />
            </div>
            <div v-else class="no-screenshot">
              <el-icon><Picture /></el-icon>
              <p>暂无截图</p>
            </div>
            
            <div class="actions">
              <el-button type="primary" @click="captureScreen" :loading="isLoading">
                {{ isLoading ? '截图中...' : '截取屏幕' }}
              </el-button>
              <el-button 
                type="success" 
                @click="recognizeUI" 
                :loading="isRecognizing"
                :disabled="!currentScreenshot || isLoading"
              >
                {{ isRecognizing ? '解析UI中...' : '识别UI' }}
              </el-button>
            </div>
          </div>  <!-- screenshot-area 的结束标签 -->
          
          <div class="ui-structure">
            <h3>UI结构</h3>
            <el-input
              v-model="uiStructure"
              type="textarea"
              :rows="10"
              placeholder="UI结构将在识别后显示"
              :disabled="isLoading"
            />
          </div>
        </div>  <!-- left-panel 的结束标签 -->
        
        <div class="right-panel">
          <div class="testcase-form">
            <h3>测试用例信息</h3>
            <el-form :model="testCaseForm" label-width="100px">
              <el-form-item label="名称">
                <el-input v-model="testCaseForm.name" placeholder="测试用例名称" />
              </el-form-item>
              <el-form-item label="描述">
                <el-input v-model="testCaseForm.description" placeholder="测试用例描述" />
              </el-form-item>
            </el-form>
            
            <el-button 
              type="primary" 
              @click="generateTestCase" 
              :disabled="!uiStructure || isLoading"
              :loading="isGenerating"
            >
              {{ isGenerating ? '生成中...' : '生成测试用例' }}
            </el-button>
          </div>
          
          <div class="testcase-result">
            <h3>测试用例</h3>
            <el-input
              v-model="testCaseContent"
              type="textarea"
              :rows="15"
              placeholder="生成的测试用例将显示在这里"
              :disabled="isLoading"
            />
            
            <div class="actions">
              <el-button type="success" @click="saveTestCase" :disabled="!testCaseContent || isLoading">
                保存测试用例
              </el-button>
              <el-button type="info" @click="copyTestCase" :disabled="!testCaseContent">
                复制到剪贴板
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="test-cases-list">
        <h3>已保存的测试用例</h3>
        <div class="table-container">
          <el-table :data="testCases" style="width: 100%">
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="createdAt" label="创建时间" :formatter="formatTime" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" @click="viewTestCase(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import { ref, onMounted, watch, nextTick } from 'vue' 
  import { useStore } from 'vuex'
  import { ElMessage } from 'element-plus'
  import { Picture } from '@element-plus/icons-vue'
  import api from '@/utils/api'
  
  export default {
    name: 'TestCaseView',
    components: {
      Picture  // 注册组件
    },
    setup() {
      const store = useStore()
      const currentScreenshot = ref(null)
      const uiStructure = ref(null)
      const testCaseContent = ref('')  // 添加缺失的响应式变量
      const isLoading = ref(false)
      const isRecognizing = ref(false)  // 添加新的状态变量
      const isGenerating = ref(false)
      const testCases = ref([])
      const testCaseForm = ref({
        name: '',
        description: ''
      })
  
      // 使用 onMounted 钩子加载测试用例
      onMounted(async () => {
        await store.dispatch('loadTestCases')
        testCases.value = store.state.testCases
      })
  
      const recognizeUI = async () => {
        if (!currentScreenshot.value) {
          ElMessage.warning('请先截取屏幕')
          return
        }

        try {
          isRecognizing.value = true  // 使用新的状态变量
          const response = await api.post('/testcase/recognize', {
            screenshotPath: currentScreenshot.value
          })
          
          // 检查响应数据
          if (response.data.error) {
            ElMessage.error('UI识别失败: ' + response.data.error)
            return
          }
          
          // 处理响应数据
          if (response.data.rawResponse) {
            // 尝试提取 JSON 部分
            const jsonMatch = response.data.rawResponse.match(/```json\n([\s\S]*?)(?:\n```|$)/)
            if (jsonMatch && jsonMatch[1]) {
              try {
                let jsonStr = jsonMatch[1].trim()
                // 处理特殊值
                jsonStr = jsonStr
                  .replace(/:\s*Infinity/g, ': "Infinity"')  // 处理 Infinity
                  .replace(/:\s*-Infinity/g, ': "-Infinity"')  // 处理 -Infinity
                  .replace(/:\s*NaN/g, ': "NaN"')  // 处理 NaN
                  .replace(/,\s*([}\]])/g, '$1')  // 移除多余的逗号
                  .replace(/\s+/g, ' ')   // 规范化空白字符
                  .replace(/,\s*([}\]])/g, '$1')  // 移除多余的逗号
                
                const jsonData = JSON.parse(jsonStr)
                uiStructure.value = JSON.stringify(jsonData, null, 2)
              } catch (e) {
                console.error('JSON解析失败:', e)
                uiStructure.value = response.data.rawResponse
              }
            } else {
              uiStructure.value = response.data.rawResponse
            }
          } else {
            uiStructure.value = JSON.stringify(response.data, null, 2)
          }
          
          ElMessage.success('UI识别完成')
        } catch (error) {
          ElMessage.error('UI识别失败: ' + (error.response?.data?.message || error.message))
        } finally {
          isRecognizing.value = false  // 重置状态
        }
      }
      const generateTestCase = async () => {
        if (!uiStructure.value) {
          ElMessage.warning('请先识别UI')
          return
        }

        try {
          isGenerating.value = true
          testCaseContent.value = '' // 清空之前的内容
          
          // 构建请求数据
          const requestData = {
            uiStructure: uiStructure.value,
            name: testCaseForm.value.name,
            description: testCaseForm.value.description
          }
          
          // 发送普通 POST 请求
          const response = await api.post('/testcase/generate', requestData)
          
          // 获取返回的内容
          const content = response.data.content
          
          // 使用打字机效果显示内容
          let index = 0
          const typeWriter = async () => {  // 添加 async
            if (index < content.length) {
              testCaseContent.value += content.charAt(index)
              index++
              // 添加自动滚动逻辑
              await nextTick()
              const textarea = document.querySelector('.testcase-result textarea')
              if (textarea) {
                textarea.scrollTop = textarea.scrollHeight
              }
              setTimeout(typeWriter, 10)
            } else {
              isGenerating.value = false
              ElMessage.success('测试用例生成完成')
            }
          }
          
          typeWriter()

        } catch (error) {
          console.error('生成测试用例失败:', error)
          isGenerating.value = false
          ElMessage.error('生成测试用例失败: ' + error.message)
        }
      }
  
      const saveTestCase = async () => {
        if (!testCaseContent.value) {
          ElMessage.warning('请先生成测试用例')
          return
        }
        
        testCaseForm.value.content = testCaseContent.value
        testCaseForm.value.screenshotPath = currentScreenshot.value
        testCaseForm.value.uiStructure = uiStructure.value
        
        try {
          await store.dispatch('createTestCase', testCaseForm.value)
          ElMessage.success('测试用例保存成功')
          
          // 刷新测试用例列表
          await store.dispatch('loadTestCases')
          testCases.value = store.state.testCases
          
          // 重置表单
          testCaseForm.value = {
            name: '',
            description: '',
            content: '',
            screenshotPath: '',
            uiStructure: ''
          }
        } catch (error) {
          ElMessage.error('保存测试用例失败: ' + error.message)
        }
      }
      
      const copyTestCase = () => {
        try {
          // Create a temporary textarea element
          const textarea = document.createElement('textarea')
          textarea.value = testCaseContent.value
          document.body.appendChild(textarea)
          
          // Select and copy the text
          textarea.select()
          document.execCommand('copy')
          
          // Clean up
          document.body.removeChild(textarea)
          
          ElMessage.success('已复制到剪贴板')
        } catch (error) {
          console.error('复制失败:', error)
          ElMessage.error('复制失败')
        }
      }
      
      const viewTestCase = (testCase) => {
        testCaseContent.value = testCase.content
        uiStructure.value = testCase.uiStructure
        if (testCase.screenshotPath) {
          store.commit('SET_CURRENT_SCREENSHOT', testCase.screenshotPath)
        }
      }
      
      const imageUrl = ref('')  // Add this line
      
      // Modify getImageUrl to update imageUrl
      const getImageUrl = async (path) => {
        if (!path) {
          imageUrl.value = ''
          return
        }
        try {
          const fileName = path.split('\\').pop()
          if (!fileName) {
            imageUrl.value = ''
            return
          }
          
          const response = await api.get(`/screenshots/base64/${encodeURIComponent(fileName)}`)
          imageUrl.value = `data:image/png;base64,${response.data}`
        } catch (error) {
          console.error('获取图片URL失败:', error)
          imageUrl.value = ''
        }
      }
      
      // Watch for changes to currentScreenshot
      watch(currentScreenshot, (newPath) => {
        getImageUrl(newPath)
      })
      
      const formatTime = (row, column, cellValue) => {
        if (!cellValue) return ''
        const date = new Date(cellValue)
        return date.toLocaleString()
      }
      
      const captureScreen = async () => {
        try {
          isLoading.value = true
          const response = await store.dispatch('captureScreen')
          currentScreenshot.value = response
          ElMessage.success('截图成功')
        } catch (error) {
          ElMessage.error('截图失败: ' + error.message)
        } finally {
          isLoading.value = false
        }
      }
      
      return {
        currentScreenshot,
        uiStructure,
        testCaseForm,
        testCaseContent,
        isLoading,
        isGenerating,
        isRecognizing,  // 确保这行存在
        testCases,
        recognizeUI,
        generateTestCase,
        saveTestCase,
        copyTestCase,
        viewTestCase,
        getImageUrl,
        formatTime,
        imageUrl,
        captureScreen,
      }
    }
  }
  </script>
  
  <style scoped>
  .testcase-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
  }
  
  .content {
    display: flex;
    gap: 20px;
    margin: 20px 0;
    flex: 1;
  }
  
  .left-panel, .right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .screenshot-area {
    border: 1px solid #eee;
    border-radius: 5px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .screenshot {
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
  }
  
  .screenshot img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }
  
  .no-screenshot {
    height: 300px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f5f5f5;
    color: #999;
  }
  
  .no-screenshot .el-icon {
    font-size: 48px;
    margin-bottom: 10px;
  }
  
  .actions {
    display: flex;
    gap: 10px;
    justify-content: center;
  }
  
  .ui-structure, .testcase-form, .testcase-result {
    border: 1px solid #eee;
    border-radius: 5px;
    padding: 15px;
  }
  
  .test-cases-list {
    margin-top: 20px;
    border: 1px solid #eee;
    border-radius: 5px;
    padding: 15px;
    display: flex;
    flex-direction: column;
  }

  .table-container {
    max-height: 300px;
    overflow-y: auto;
  }

  /* 自定义滚动条样式 */
  .table-container::-webkit-scrollbar {
    width: 6px;
  }

  .table-container::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
  }

  .table-container::-webkit-scrollbar-track {
    background-color: #f5f5f5;
  }

  /* 添加打字机效果相关样式 */
  .typing-effect {
    white-space: pre-wrap;
    overflow-wrap: break-word;
  }
  
  .typing-effect textarea {
    transition: color 0.1s;
  }
  
  @keyframes typing {
    from { width: 0 }
    to { width: 100% }
  }
  </style>